//
//  IM_Service+Write.m
//  SportSocial
//
//  Created by yull on 14/12/13.
//  Copyright (c) 2014年 yull. All rights reserved.
//

#import "IM_Service+Write.h"
#import "Parser.h"

#import "Message.pb.h"
#import "Server.pb.h"
#import "Common.pb.h"

@implementation IM_Service (Write)

- (void)sendData:(NSData *)pbData protocolId:(UInt16)pId
{
    NSMutableData *data = [NSMutableData data];
    
    [Parser appendUInt32:pbData.length+2 to:data];
    [Parser appendUInt16:pId to:data];
    [data appendData:pbData];
    
    [self.asyncSocket writeData:data withTimeout:-1 tag:0];
    
    if (self.heartbeatTimer) {
        dispatch_source_cancel(self.heartbeatTimer);
    }
    
    self.heartbeatTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.serviceQueue);
    
    dispatch_source_set_timer(self.heartbeatTimer,
                              dispatch_time(DISPATCH_TIME_NOW, HEART_TIME_INTERVAL * NSEC_PER_SEC),
                              HEART_TIME_INTERVAL * NSEC_PER_SEC, 0);
    
    dispatch_source_set_event_handler(self.heartbeatTimer, ^{
        [self sendHeartBeat];
    });
    
    dispatch_resume(self.heartbeatTimer);
}

- (void)sendHeartBeat
{
    if ([self isConnected]) {
        [self sendData:nil protocolId:IM_SEND_HEART_BEAT];
    }
}

@end
